package com.mrd.modules.generator.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrd.base.utils.FormBeanUtil;
import com.mrd.base.utils.JsonBinder;
import com.mrd.base.utils.PageUtils;
import com.mrd.base.utils.Query;
import com.mrd.base.utils.R;
import com.mrd.modules.generator.entity.CodegenColumnEntity;
import com.mrd.modules.generator.entity.CodegenTableEntity;
import com.mrd.modules.generator.service.CodegenColumnService;
import com.mrd.modules.generator.service.CodegenTableService;
import com.mrd.modules.generator.service.SysGeneratorService;


/**
 * 代码生成信息
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-08-06 17:12:15
 */
@Controller
@RequestMapping("codegentable")
public class CodegenTableController {
  @Autowired
  private CodegenTableService codegenTableService;
  @Autowired
  private SysGeneratorService sysGeneratorService;
  @Autowired
  private CodegenColumnService codegenColumnService;

  /**
   * 列表
   */
  @ResponseBody
  @RequestMapping("/list")
  public R list(@RequestParam Map<String, Object> params) {
    // 查询列表数据
    Query query = new Query(params);
    CodegenTableEntity codegenTable = FormBeanUtil.get(params, CodegenTableEntity.class);
    PageHelper.startPage(query.getPage(), query.getLimit());
    List<CodegenTableEntity> codegenTableList = codegenTableService.queryPageList(codegenTable);
    PageInfo<CodegenTableEntity> pi = new PageInfo<CodegenTableEntity>(codegenTableList);
    PageUtils pageUtil = new PageUtils(codegenTableList, Integer.parseInt(pi.getTotal() + ""),
        query.getLimit(), query.getPage());

    return R.ok().put("page", pageUtil);
  }


  /**
   * 信息
   */
  @ResponseBody
  @RequestMapping("/info/{id}")
  public R info(@PathVariable("id") String id) {
    CodegenTableEntity codegenTable = codegenTableService.queryObject(id);

    return R.ok().put("codegenTable", codegenTable);
  }

  /**
   * 保存
   */
  @ResponseBody
  @RequestMapping(value = "/save")
  public R save(@RequestBody CodegenTableEntity codegenTable, HttpServletRequest request) {
    List<CodegenColumnEntity> columnList =
        JSONObject.parseArray(codegenTable.getColumnsStr(), CodegenColumnEntity.class);
    // todo
    codegenTableService.update(codegenTable);
    if (columnList != null && columnList.size() > 0) {
      for (CodegenColumnEntity column : columnList) {
        codegenColumnService.update(column);
      }
    }
    return R.ok();
  }

  /**
   * 修改
   */
  @ResponseBody
  @RequestMapping("/update")
  public R update(@RequestBody CodegenTableEntity codegenTable) {
    codegenTableService.update(codegenTable);

    return R.ok();
  }

  /**
   * 删除
   */
  @ResponseBody
  @RequestMapping("/delete")
  public R delete(@RequestBody String[] ids) {
    codegenTableService.deleteBatch(ids);

    return R.ok();
  }

  /**
   * 把要配置生成代码的表信息生成到数据库保存
   * 
   * @author han
   */
  @ResponseBody
  @RequestMapping("/code")
  public R code(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String[] tableNames = new String[] {};
    // 获取表名，不进行xss过滤
    // HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
    String tables = request.getParameter("tables");
    tableNames = JSON.parseArray(tables).toArray(tableNames);
    sysGeneratorService.saveGeneratorCode(tableNames);
    return R.ok();
  }

  /**
   * 编辑要生成代码的表信息
   * 
   * @author han
   * @param table
   * @param model
   * @param request
   * @param response
   * @return
   * @throws IOException
   */
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  public String edit(CodegenTableEntity table, Model model, HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    CodegenTableEntity tableEntity = codegenTableService.queryObject(table.getId());
    model.addAttribute("tableEntity", tableEntity);
    Map<String, Object> columnSearchMap = new HashMap<String, Object>();
    columnSearchMap.put("tableId", tableEntity.getId());
    columnSearchMap.put("sidx", "sort");
    columnSearchMap.put("order", "desc");
    List<CodegenColumnEntity> columns = codegenColumnService.queryList(columnSearchMap);
    JsonBinder jsonBinder = JsonBinder.buildNormalBinder();
    String columnsJson = jsonBinder.toJson(columns);
    model.addAttribute("columns", columnsJson);
    return "/generator/edit";
  }

  /**
   * 生成代码
   */
  @RequestMapping(value = "/createCode")
  public void createCode(String ids, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String[] idAry = new String[] {};
    idAry = JSON.parseArray(ids).toArray(idAry);

    byte[] data = codegenTableService.advGeneratorCode(idAry);

    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"codegenSource.zip\"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");

    IOUtils.write(data, response.getOutputStream());
  }
}
